/*
 * @Author: szx
 * @Date: 2023-03-27 19:09:13
 * @LastEditTime: 2023-03-28 15:57:41
 * @Description: 
 * @FilePath: \learn\fullstackopen\part1\part1\src\App.js
 */
import { useState, useEffect } from 'react'
import axios from 'axios';
import Filter from './components/Filter';


const App = () => {

  useEffect(() => {
    axios
      .get('https://restcountries.com/v3.1/all')
      .then(response => {
        console.log('promise fulfilled')
        setCoutries(response.data)
      })
  }, []);
  const [countries, setCoutries] = useState([]);
  const [filter, setFilter] = useState('');

  const handleFilterChange = (event) => {
    setFilter(event.target.value)
  }

  return (
    <div>
      <Filter filter={filter} handleFilter={handleFilterChange} />

      <Countries countries={countries} filterValue={filter} />
    </div>
  )
}

const Countries = ({ countries, filterValue }) => {
  if (filterValue === '') return (
    <p>please input something!</p>
  )
  const filterCountris = countries.filter((country) =>
    country.name.common.toLowerCase().startsWith(filterValue.toLowerCase())
  )
  if (filterCountris.length > 10) return (
    <p>too many countries, specify another filter</p>
  );
  else if (filterCountris.length > 1) return (
    filterCountris.map((country) => <Country key={country.name.common} country={country} />)
  )
  else if (filterCountris.length === 1) {
    return (
      <CountryInfo country={filterCountris[0]} />
    )
  }
  else return <p>no match!</p>
  // return (
  //   countries.map((country) => <p >{country}</p>)
  // )
}
const Country = ({ country }) => {
  const [show, setShow] = useState(false);
  const handleShow = () => {
    setShow(!show)
  }

  return (
    <li>
      {country.name.common}<button onClick={handleShow}> show</button>
      {show && <CountryInfo country={country} />}
    </li>
  )

}
const CountryInfo = ({ country }) => {
  const languages = Object.values(country.languages)
  console.log(country.languages)
  return (
    <div>
      <h3>
        {country.name.common}
      </h3>
      <p>capital:{country.capital[0]}</p>
      <p>area:{country.area}</p>
      <h4>language:</h4>
      <ul>
        {languages.map((lang) => <li key={lang}>{lang}</li>)}
      </ul>
      <img src={country.flags.png} alt={country.name.common} width="33%" height="33%" />
    </div>
  )
}
export default App